<template>
  <div class="progress-bar-template">
    <div class="progress-bar-container" @click="seek">
      <div class="progress-bar" ref="progressBar" @mousedown="onDragStart">
        <div class="progress" :style="{ width: `${currentProgress}%` }"></div>
        <div class="thumb" :style="{ left: `${currentProgress}%` }" @mousedown.stop="onDragStart"></div>
      </div>
    </div>
    <div class="time-bottom">
      <div class="icon" @click="handlePause">
        <PauseOutlined v-if="status" :style="{ fontSize: '20px' }" />
        <CaretRightOutlined :style="{ fontSize: '20px' }" v-else />
      </div>
      <div class="time">{{ getCurrentTime(second) }} / {{ endTime }}</div>
    </div>
  </div>
</template>

<script setup>
  import { ref, onMounted, onUnmounted } from 'vue';
  import { dateFormat } from '/@/utils/date';

  const emit = defineEmits(['updateTime']);

  const currentProgress = ref(0); // 当前播放进度百分比（0 - 100）
  const isDragging = ref(false);
  const progressBar = ref(null);
  const status = ref(false);
  const second = ref(0);
  const startTime = ref('');
  const endTime = ref('');
  let total = 0; // 一共多少秒
  let col = 0; // 一秒占 % 多少

  // 监听鼠标移动事件，用于拖动进度条
  const onDragStart = (event) => {
    stop();
    isDragging.value = true;
    updateProgress(event);
    window.addEventListener('mousemove', updateProgress);
    window.addEventListener('mouseup', onDragEnd);
  };

  // 释放鼠标时停止拖动
  const onDragEnd = () => {
    isDragging.value = false;
    window.removeEventListener('mousemove', updateProgress);
    window.removeEventListener('mouseup', onDragEnd);
    updateTimeFn();
  };

  // 更新进度条
  const updateProgress = (event) => {
    if (!isDragging.value) return;

    const { left, width } = progressBar.value.getBoundingClientRect();
    const clickPosition = event.clientX - left;
    const newProgress = (clickPosition / width) * 100;

    currentProgress.value = Math.max(0, Math.min(newProgress, 100)); // 限制范围在 0 - 100 之间
  };

  // 点击进度条时跳转到点击位置
  const seek = (event) => {
    const { left, width } = progressBar.value.getBoundingClientRect();
    const clickPosition = event.clientX - left;
    currentProgress.value = (clickPosition / width) * 100;
  };

  function initProgress(row) {
    startTime.value = row.startTime;
    endTime.value = row.endTime;
    total = (+new Date(endTime.value) - +new Date(startTime.value)) / 1000;
    col = 100 / total;
    handlePause();
  }

  function handlePause() {
    if (status.value) {
      status.value = false;
      stop();
    } else {
      status.value = true;
      start();
    }
  }

  function updateTimeFn() {
    stop();
    setTimeout(() => {
      second.value = Math.round((currentProgress.value / 100) * total);
      emit('updateTime', getCurrentTime(second.value), 'active');
      if (status.value) {
        start();
      }
    }, 0);
  }

  let interval = null;

  function start() {
    interval = setInterval(() => {
      if (currentProgress.value < 100) {
        let number = currentProgress.value + col;
        if (number > 100) {
          number = 100;
        }
        currentProgress.value = number;
        second.value += 1;
        emit('updateTime', getCurrentTime(second.value), 'passive');
      } else {
        clearInterval(interval);
      }
    }, 1000);
  }

  function end() {
    if (interval) {
      clearInterval(interval);
    }
    status.value = false;
    currentProgress.value = 0;
    total = 0;
    col = 0;
    startTime.value = '';
    endTime.value = '';
    second.value = 0;
  }

  function stop() {
    if (interval) {
      clearInterval(interval);
    }
  }

  function getCurrentTime(num) {
    return dateFormat(+new Date(startTime.value) + num * 1000);
  }

  defineExpose({ initProgress, start, end, stop });

  // 注册和注销事件监听
  onMounted(() => {
    window.addEventListener('mouseup', onDragEnd);
  });

  onUnmounted(() => {
    window.removeEventListener('mouseup', onDragEnd);
  });
</script>

<style scoped lang="less">
  .progress-bar-container {
    width: 100%;
    padding: 10px 0;
    user-select: none;
    .progress-bar {
      width: 100%;
      height: 10px;
      background-color: #e0e0e0;
      border-radius: 5px;
      position: relative;
      cursor: pointer;
      .progress {
        height: 100%;
        background-color: #1d57a6;
        border-radius: 5px;
        position: relative; /* 用于内部的 progress-marker 定位 */
        transition: width 0.1s linear;
        border: 1px solid #fff;
      }
      .thumb {
        width: 18px;
        height: 18px;
        background-color: #1d57a6;
        border-radius: 50%;
        position: absolute;
        top: 50%;
        transform: translate(-50%, -50%);
        cursor: pointer;
        transition: left 0.1s linear;
        border: 2px solid #fff;
      }
    }
  }
  .time-bottom {
    margin-bottom: 5px;
    display: flex;
    align-items: center;
    height: 25px;
    color: #fff;
    .icon {
      cursor: pointer;
      margin-right: 10px;
    }
  }
</style>
